package acme.ws;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JSONServlet extends HttpServlet {
	
	private static final long serialVersionUID = 8893392323187332094L;
	
	private static Gson gson = null;

	protected void returnJSON(Object obj, HttpServletResponse response){
		if(obj != null){
			String json = getGson().toJson(obj);		
			this.returnJSON(json, response);
		}
	}
	
	protected void returnJSON(String json, HttpServletResponse response){
		PrintWriter out = null;		
		response.setContentType("application/json");
		try {
			out = response.getWriter();
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out != null){ 
				out.close();
			}
		}
		out.flush();
	}
	
	public static Gson getGson(){
		if(gson == null){
			GsonBuilder gb = new GsonBuilder();
			gb.setPrettyPrinting();
			gson = gb.create();
		}
		return gson;
	}
}
